package com.service.weChatWifiLogin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.config.constant.ApiUrlConstants;
import com.service.config.utils.*;
import com.service.weChatWifiLogin.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.service.config.utils.DateUtil.*;

/**
 * @program: CloudCampusService
 * @description: 云管理Api封装
 * @author: rui
 * @create: 2021-03-31 14:26
 **/

@Component
@Slf4j
public class CloudCampusApi implements ApiUrlConstants {

    @Resource
    RestTemplate restTemplate;
    @Resource
    RedisUtil redisUtil;

    /**
     * 获取token
     *
     * @param username
     * @param password
     * @param requestHeaders
     * @return
     */
    public String getToken(String username, String password, HttpHeaders requestHeaders, String domain) {
        //获取token
        Map map = new HashMap();
        map.put("userName", username);
        map.put("password", password);
        try {
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.exchange("https://" + domain + CLOUD_CAMPUS_TOKEN_URL, HttpMethod.POST, requestEntity, JSONObject.class);
            return response.getBody().getJSONObject("data").getString("token_id");
        } catch (Exception e) {
            log.error("debug Token ==>" + e.getMessage());
            return null;
        }
    }


    /**
     * 获取站点site
     *
     * @param requestHeaders
     * @return
     */
    public List<SiteDto> getSites(HttpHeaders requestHeaders, String domain) {
        //获取站点
        boolean flag = true;
        int pageIndex = 1;
        List<SiteDto> siteDtos = new ArrayList<>();
        try {
            while (flag) {
                HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.exchange("https://" + domain + SITE_URL + pageIndex, HttpMethod.GET, requestEntity, JSONObject.class);
                JSONArray data = response.getBody().getJSONArray("data");
                if (!data.isEmpty()) {
                    siteDtos.addAll(data.toJavaList(SiteDto.class));
                    pageIndex++;
                } else {
                    flag = false;
                }
            }
            return siteDtos;
        } catch (Exception e) {
            log.error("debug getSites ==>" + e.getMessage());
            return null;
        }
    }

    /**
     * 与云管理交互，增加ssid或更新
     * @param shopInfoDto
     * @param sites
     * @param token
     * @throws Exception
     */
    public void addSsId(ShopInfoDto shopInfoDto,List<SiteDto> sites,HttpHeaders token) throws Exception {
        SsidConfigDto ssidConfigDto = new SsidConfigDto();
        ssidConfigDto.setName(shopInfoDto.getSsidFlag()+"_"+shopInfoDto.getSsidName());
        AuthContentDto authContentDto = new AuthContentDto();
        authContentDto.setSecurityKey(shopInfoDto.getSsidPassword());
        ssidConfigDto.setSsidAuth(authContentDto);
        PolicyContentDto policyContentDto = new PolicyContentDto();

        //限速
        String upLimit = shopInfoDto.getUpLimit();
        if (StringUtils.isNotEmpty(upLimit) && !"0".equals(upLimit)) {
            RateLimitContentDto rateLimitContentDto = new RateLimitContentDto();
            rateLimitContentDto.setUpEnable(true);
            BigDecimal kbBySeconds = new BigDecimal(upLimit).divide(new BigDecimal("128"), 1, BigDecimal.ROUND_UP);
            rateLimitContentDto.setUpLimit(kbBySeconds.toString());
            policyContentDto.setSsidRateLimit(rateLimitContentDto);
        }
        ssidConfigDto.setSsidPolicy(policyContentDto);
        HttpEntity<SsidConfigDto> requestEntity = new HttpEntity<>(ssidConfigDto, token);
        //新增SSID信息
        if (!redisUtil.exist(shopInfoDto.getId())) {
            for (SiteDto siteId : sites) {
                //站点与SSID是一对多的关系
                //添加之后需要绑定站点与SSID的关系
                ResponseEntity<JSONObject> response = restTemplate.exchange(URL_FIRST+shopInfoDto.getDomain()+SS_ID_ADD_URL + siteId.getId() + "/apssid", HttpMethod.POST, requestEntity, JSONObject.class);
                JSONObject responseBody = response.getBody();
                if ("0".equals(responseBody.getString("errcode"))) {
                    SsidDto data = ModelMapperUtil.strictMap(responseBody.getJSONObject("data"), SsidDto.class);
                    data.setSiteId(siteId.getId());
                    redisUtil.leftPush(shopInfoDto.getId(), JsonXMLUtils.obj2json(data));
                }
            }
        }else { // 更新ssid
            List list = redisUtil.getList(shopInfoDto.getId());
            redisUtil.delete(shopInfoDto.getId());
            for (SiteDto siteId : sites) {
                //站点与SSID是一对多的关系
                //添加之后需要绑定站点与SSID的关系
                List<SsidDto> ssidDtoList = new ArrayList<>();
                for (Object o : list) {
                    ssidDtoList.add(JsonXMLUtils.json2obj(o.toString(),SsidDto.class));
                }
                List<SsidDto> collect = ssidDtoList.stream().filter(ssidDto -> ssidDto.getSiteId().equals(siteId.getId())).collect(Collectors.toList());
                if (collect.size()>0) {
                    ResponseEntity<JSONObject> response = restTemplate.exchange(URL_FIRST+shopInfoDto.getDomain()+ApiUrlConstants.SS_ID_UPDATE_URL + siteId.getId() + "/apssid/" + collect.get(0).getId(), HttpMethod.PUT, requestEntity, JSONObject.class);
                    JSONObject responseBody = response.getBody();
                    if ("0".equals(responseBody.getString("errcode"))) {
                        SsidDto data = ModelMapperUtil.strictMap(responseBody.getJSONObject("data"), SsidDto.class);
                        data.setSiteId(siteId.getId());
                        redisUtil.leftPush(shopInfoDto.getId(), JsonXMLUtils.obj2json(data));
                    }
                }
            }
        }
    }
    public void deleteSsId(String id, HttpHeaders requestHeaders,String domain) throws Exception {
        List<SsidDto> ssidDtoList = new ArrayList<>();
        if (redisUtil.exist(id)){
            List list = redisUtil.getList(id);
            for (Object o : list) {
                ssidDtoList.add(JsonXMLUtils.json2obj(o.toString(),SsidDto.class));
            }
            redisUtil.delete(id);
            ssidDtoList.stream().forEach(ssidDto -> {
                HashMap map = new HashMap();
                map.put("ids",Arrays.asList(ssidDto.getId()));
                HttpEntity<Map> requestEntity = new HttpEntity<>(map, requestHeaders);
                ResponseEntity<JSONObject> response = restTemplate.exchange(URL_FIRST+domain+ApiUrlConstants.SS_ID_DEL_URL + ssidDto.getSiteId() + "/apssid", HttpMethod.DELETE, requestEntity, JSONObject.class);
                JSONObject responseBody = response.getBody();
                if ("0".equals(responseBody.getString("errcode"))) {
                    log.info("success");
                }

            });
        }
    }
}
